#coding:utf8
from django.shortcuts import render
from django.views.generic import TemplateView,View
from django.contrib.auth import authenticate, login,logout
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

# Create your views here.
class LoginView(View):
    def get(self,request):
        return render(request, "login.html", {"is_get":True})
    def post(self,request):
        user_name = request.POST.get("username", "")
        pass_word = request.POST.get("password", "")
        if user_name and pass_word:
            user = authenticate(username=user_name, password=pass_word)
            if user is not None:
                login(request, user)
                return HttpResponseRedirect('/')
            else:
                return render(request, "login.html", {"msg": "用户名或密码错误"})
        else:
            return render(request, "login.html", {"msg": "用户名或密码错误"})

class LogoutView(View):
    def get(self,request):
        logout(request)
        return HttpResponseRedirect(reverse("login_view"))
    def post(self,request):
        logout(request)
        return HttpResponseRedirect(reverse("login_view"))

class EditPasswordView(View):
    def post(self,request):
        user = request.user
        old_password = request.POST.get("old_password", "")
        new_password = request.POST.get("new_password", "")
        new_password2 = request.POST.get("new_password2", "")
        data = {'status':False,'msg':''}
        if old_password and new_password and new_password2:
            old_user = authenticate(username=user.username, password=old_password)
            if old_user is not None:
                if new_password == new_password2:
                    old_user.set_password(new_password)
                    old_user.save()
                    data['status'] = True
                    data['msg'] = u'密码修改成功'
                else:
                    data['msg'] = u'两次密码不一致'
            else:
                data['msg'] = u'原始密码错误'
        else:
            data['msg'] = u'密码不能为空'
        return JsonResponse(data)